package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.RequestParm;
import cn.itcast.hotel.pojo.ResponseParms;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    RestHighLevelClient client;
    @Override
    public ResponseParms search(RequestParm parms) throws IOException {
        //创建复核查询工具
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        创装request
        SearchRequest request = new SearchRequest("hotel");
//        复核查询封装
        extracted(parms, boolQuery, request);
//    按照地理位置排序
        String location = parms.getLocation();
        if (location != null && location !=""){
            request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(location)).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
        }
//        实现广告置顶 function score
        FunctionScoreQueryBuilder functionquerry = QueryBuilders.functionScoreQuery(boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                        QueryBuilders.termQuery("isAd", true),
                        ScoreFunctionBuilders.weightFactorFunction(10)
                )
        });

        request.source().query(functionquerry);
//        发送请求
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
//        给responseparms赋值并返回
        ResponseParms responseParms = new ResponseParms();
        ResponseParms extracted = extracted(search, responseParms);
        return extracted;

    }

    @Override
    public Map<String, List<String>> filters(RequestParm parms) throws IOException {

        //封装request
        SearchRequest request = new SearchRequest("hotel");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        extracted(parms, boolQuery, request);
        request.source().size(0);
        request.source().aggregation(AggregationBuilders.terms("brandagg").field("brand").size(10));
        request.source().aggregation(AggregationBuilders.terms("cityagg").field("city").size(10));
        request.source().aggregation(AggregationBuilders.terms("staragg").field("starName").size(10));
        ArrayList<String> topics = new ArrayList<>();
        topics.add("brandagg");
        topics.add("cityagg");
        topics.add("staragg");
        request.source().query(boolQuery);
        //发送请求
        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
        //拿到结果回显到前端
        Map<String, List<String>> stringListMap = extracted1(resp, topics);
        return stringListMap;
    }

    @Override
    public List<String> suggestion(String key) throws IOException {
        //创建请求
        SearchRequest request = new SearchRequest("hotel");
        //构建查询条件
        request.source().suggest(new SuggestBuilder().addSuggestion("mysuggest", SuggestBuilders.
                completionSuggestion("suggestion").prefix(key).skipDuplicates( true).size(10)));
        //发送请求
        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
        //解析查询结果
        Suggest suggest = resp.getSuggest();
        CompletionSuggestion mysuggest = suggest.getSuggestion("mysuggest");
        List<CompletionSuggestion.Entry.Option> options = mysuggest.getOptions();
        ArrayList<String> resultlist = new ArrayList<>(options.size());
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            resultlist.add(text);
        }
        return resultlist;
    }

    @Override
    public void insertorupdatehotel(Long id) throws IOException {
        Hotel hotel = getById(id);
        HotelDoc hotelDoc = new HotelDoc(hotel);
        String json = JSON.toJSONString(hotelDoc);
//        创建request
        IndexRequest request = new IndexRequest("hotel").id(id.toString());
        request.source(json, XContentType.JSON);
//        发送数据请求向es
        client.index(request, RequestOptions.DEFAULT);
    }

    @Override
    public void deletehotel(Long id) throws IOException {
        //        穿件request
        DeleteRequest request = new DeleteRequest("hotel", id.toString());
        //发送dsl语句向es
        client.delete(request, RequestOptions.DEFAULT);
    }

    private static Map<String, List<String>> extracted1(SearchResponse resp,List<String> aggnames) {
        Aggregations aggregations = resp.getAggregations();
        HashMap<String, List<String>> maps = new HashMap<>();
        String otherbrand= "";
        for (String aggname : aggnames) {
            if ("brandagg".equals(aggname) ){
                otherbrand = "品牌";

                extracted(aggregations, maps, aggname,otherbrand);
            }
           else if ("cityagg".equals(aggname) ){
                otherbrand = "城市";
                extracted(aggregations, maps, aggname,otherbrand);
            }
           else if("staragg".equals(aggname)) {
                otherbrand = "星级";
                extracted(aggregations, maps, aggname,otherbrand);
            }

        }
        return maps;
    }

    private static void extracted(Aggregations aggregations, HashMap<String, List<String>> maps, String aggname,String otherbrand) {
        Terms terms = aggregations.get(aggname);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        ArrayList<String> strings = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String value = bucket.getKeyAsString();
            strings.add(value);
        }
        if (otherbrand.equals("品牌")){
            maps.put("brand",strings);
        } else if (otherbrand.equals("城市")) {
            maps.put("city",strings);
        }else {
            maps.put("starName",strings);
        }

    }

    private static void extracted(RequestParm parms, BoolQueryBuilder boolQuery, SearchRequest request) {
        if (ObjectUtils.isEmpty(parms.getKey())){
                boolQuery.must(QueryBuilders.matchAllQuery());
        }else{
            boolQuery.must(QueryBuilders.multiMatchQuery(parms.getKey(),"name","brand","city").type(MultiMatchQueryBuilder.Type.BEST_FIELDS));
        }
//        设置分页
        Integer page = parms.getPage();
        Integer size = parms.getSize();
        request.source().from((page-1)* size).size(size);
//        设置city
        if (parms.getCity()!=null && parms.getCity()!=""){
            boolQuery.filter(QueryBuilders.termQuery("city", parms.getCity()));
        }
//        设置查询的品牌
        if (parms.getBrand()!=null && parms.getBrand()!=""){
           boolQuery.filter(QueryBuilders.termQuery("brand", parms.getBrand()));
        }
//        星级查询
        if (parms.getStarName()!=null && parms.getStarName()!=""){
            boolQuery.filter(QueryBuilders.termQuery("starName", parms.getStarName()));
        }
        if (parms.getMinPrice()!=null && parms.getMaxPrice()!=null ){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(parms.getMinPrice()).lte(parms.getMaxPrice()));
        }
    }


    private  ResponseParms extracted(SearchResponse search,ResponseParms responseParms) {
        TotalHits totalHits = search.getHits().getTotalHits();
        //搜索结果的总条数
        long total= totalHits.value;
        responseParms.setTotal(Integer.valueOf(total+""));
        SearchHit[] hits = search.getHits().getHits();
        ArrayList<HotelDoc> hotelDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String hotelmessage = hit.getSourceAsString();
            HotelDoc hotelDoc = JSONObject.parseObject(hotelmessage, HotelDoc.class);
            hotelDocs.add(hotelDoc);
        }
        responseParms.setHotels(hotelDocs);
        return responseParms;
    }
}
